package userlogic

import (
	"OemServer/internal/svc"
	"OemServer/pb"
	"common/comCopier"
	"common/dao/model"
	"context"
	"fmt"
	"gorm.io/gorm"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListLogic {
	return &ListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

type LogicUser struct {
	UpdateTime *time.Time `gorm:"column:update_time;type:datetime(3);autoUpdateTime:true;comment:更新时间" json:"update_time"`
	NickName   string     `gorm:"column:nick_name;type:varchar(255);comment:用户名" json:"nick_name"`
	Account    string     `gorm:"column:account;type:varchar(255);comment:账号" json:"account"`
	Password   string     `gorm:"column:password;type:varchar(255);comment:密码" json:"password"`
	Phone      string     `gorm:"column:phone;type:varchar(255);comment:手机号" json:"phone"`
	Sex        string     `gorm:"column:sex;type:varchar(100);comment:性别" json:"sex"`
	UUID       string     `gorm:"column:uuid;type:varchar(255);not null;comment:暴露id" json:"uuid"`
	Address    string     `gorm:"column:address;type:varchar(255);comment:地址" json:"address"`
	Auth       int64      `gorm:"column:auth;type:bigint(20);comment:权限" json:"auth"`
	Picture    string     `gorm:"column:picture;type:varchar(255);comment:头像" json:"picture"`
	IsAdmin    int32      `gorm:"column:is_admin;type:int(3);comment:是否超级管理员" json:"is_admin"`
	Points     int32      `gorm:"column:points;type:int(20);comment:积分" json:"points"`
	RoleUUID   string     `gorm:"column:role_uuid;type:varchar(255);comment:绑定权限" json:"role_uuid"`
	RoleName   string     `protobuf:"bytes,13,opt,name=roleName,proto3" json:"roleName,omitempty"`
	Disable    int32      `gorm:"column:disable;type:int(3);default:1;comment:是否禁用  1=激活，2=禁用" json:"disable"`
}

func (l *ListLogic) List(in *pb.ListRequest) (*pb.RespUserList, error) {
	// todo: add your logic here and delete this line
	var (
		resp = pb.RespUserList{}
	)
	var (
		list  []LogicUser
		count int64
		key   = "user.nick_name"
	)
	db := l.svcCtx.DB
	table := db.Table(model.TableNameUser)
	err := table.Transaction(func(tx *gorm.DB) error {
		s1 := fmt.Sprintf("user.*,%s.role_name", model.TableNameUserRole)
		sprintf := fmt.Sprintf("LEFT JOIN user_role ON user.role_uuid = user_role.uuid")
		ls := tx.Select(s1).Joins(sprintf).Where("user.is_del=? AND "+key+" LIKE ?", 0, "%"+in.Keyword+"%")
		ls.Count(&count)
		if in.Page > 0 && in.PageSize > 0 {
			ls = ls.Offset(int((in.Page - 1) * in.PageSize)).Limit(int(in.PageSize))
		}
		if err := ls.Order("user.update_time desc").Find(&list).Error; err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	err = comCopier.CopyWithOption(&resp.List, list)
	if err != nil {
		return nil, err
	}
	resp.Total = int32(count)
	return &resp, nil
}
